﻿package wibrst.loading {
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.utils.Dictionary;
	import wibrst.utils.StringUtil;
	
	public class VSwfLoading extends VKernelLoading {
		
		private var _aLoaderInfo:Array;
		
		private var _dictLoaderProg:Dictionary;
		
		private var _aLoadUnits:Array;
		
		private var _sIdSwfLoad:String;
		
		private var _sPromptSwfLoad:String;
		
		public function get sIdSwfLoad():String { return _sIdSwfLoad; }
		
		public function get aLoadUnits():Array { return _aLoadUnits; }
		
		public function get sPromptSwfLoad():String { return _sPromptSwfLoad; }
		
		public function getLoaderInfo(idx:Number):LoaderInfo {
			return _aLoaderInfo[idx] as LoaderInfo;
		}
		
		public function VSwfLoading() {
			
		}
		
		/**
		 * 所要载入的URL数组
		 * @param	aUrlLoading
		 */
		public function startLoadingFromArr( aLoadUnits:Array ):void {
			this._aLoadUnits = aLoadUnits;
			
			var aStringsId:Array = [];
			var aStringsPrompt:Array = [];
			for each( var loadUnit:LoadUnit in aLoadUnits ) {
				aStringsId.push( loadUnit.sId );
				aStringsPrompt.push( loadUnit.sPrompt );
			}
			
			this._sIdSwfLoad = StringUtil.getStringsId( aStringsId );
			this._sPromptSwfLoad = StringUtil.getStringsId( aStringsPrompt, ", " );
			
			super.startLoading();
		}
		
		override protected function startAction( ):void{
			if(bDetailTrace) trace( "[VSwfLoading] startAction _sIdSwfLoad:", _sIdSwfLoad );
			for each( var loaderInfoOld:LoaderInfo in _aLoaderInfo ) {
				loaderInfoOld = null;
			}
			_dictLoaderProg = new Dictionary;
			_aLoaderInfo = [];
			
			//var appDomain:ApplicationDomain = new ApplicationDomain(ApplicationDomain.currentDomain);
			//var appDomain:ApplicationDomain = new ApplicationDomain(null);
			
			for ( var iter:String in _aLoadUnits ) {
				var loadUnit:LoadUnit = _aLoadUnits[iter];

				var loader:Loader = new Loader;
				var ldrInfo:LoaderInfo = loader.contentLoaderInfo as LoaderInfo;
				
				ldrInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
				ldrInfo.addEventListener(Event.OPEN, openHandler);
				ldrInfo.addEventListener(Event.COMPLETE, compHandler);
				ldrInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
				ldrInfo.addEventListener(ProgressEvent.PROGRESS, progHandler);
				loader.load(
								new URLRequest( loadUnit.sUrl ), 
								new LoaderContext( false, loadUnit.appDomain )
				);
				
				_dictLoaderProg[ldrInfo] = new LoadProgInfo;
				
				_aLoaderInfo.push(ldrInfo);
			}
		}
		
		/**
		 *  在完成所有Load后执行的动作
		 */
		override protected function compAction():void {
			super.compLoading();
			dispatchEvent(new Event(LOAD_ALL_COMP));
			clearLoadEvents();
		}
		
		/**
		 * kernel process for loader ProgressEvent.PROGRESS
		 * @param	e the loader's ProgressEvent event
		 */
		private function progHandler(e:ProgressEvent):void {
			
			var progInfo:LoadProgInfo;
			var ldrInfo:LoaderInfo;
			
			/// get current loaderInfo
			ldrInfo= e.currentTarget as LoaderInfo;
			
			progInfo = _dictLoaderProg[ldrInfo] as LoadProgInfo;
			progInfo.bytesLoaded = e.bytesLoaded;
			progInfo.bytesTotal = e.bytesTotal;
			
			//trace( this, "\t", progInfo.bytesLoaded, "/", progInfo.bytesTotal, "~~~~~~", ldrInfo, CommUtils.getBaseName(ldrInfo.url) );
			
			/// stat thru
			var nLoaded:Number = 0;
			var nTotal:Number = 0;
			
			var bAllAvailable:Boolean = true;
			for each( progInfo in _dictLoaderProg) {
				if( progInfo.bytesTotal){
					nLoaded += progInfo.bytesLoaded;
					nTotal += progInfo.bytesTotal;
				}else {
					bAllAvailable = false;
				}
			}
			
			/// stat total
			if (bAllAvailable) {
				var nPercent:Number = nLoaded / nTotal;
				var sPercent:String = int(nPercent * 100).toString() + "%";
				progAction( nPercent, sPercent );
				if (nLoaded == nTotal) {
					if(bDetailTrace) trace( "[VSwfLoading] progHandler - bytes ready" );
				}
			}
		}
		
		private function compHandler(e:Event):void {
			var loaderInfo:LoaderInfo = e.currentTarget as LoaderInfo;
			loaderInfo.removeEventListener(Event.COMPLETE, compHandler);
			traceLoaderInfoEvent(e);
			
			if (++nComp == _aLoaderInfo.length) {
				compAction();
			}
		}
		
		/// events clear
		private function clearLoadEvents():void{
			for each( var ldrInfo:LoaderInfo in _aLoaderInfo) {
				ldrInfo.removeEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
				ldrInfo.removeEventListener(Event.OPEN, openHandler);
				ldrInfo.removeEventListener(Event.COMPLETE, openHandler);
				ldrInfo.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
				ldrInfo.removeEventListener(ProgressEvent.PROGRESS, progHandler);
			}
		}
		
		/// http status handlers
		private function ioErrorHandler(e:IOErrorEvent):void {
			if ( bDetailTrace ) traceLoaderInfoEvent ( e ) ;
			this.compHandler ( e ) ;
		}
		
		private function openHandler(e:Event):void {
			if(bDetailTrace) traceLoaderInfoEvent(e);
		}
		
		private function httpStatusHandler(e:HTTPStatusEvent):void {
			if(bDetailTrace) traceLoaderInfoEvent(e);
		}
		
		/// debug
		private function traceLoaderInfoEvent(e:Event):void{
			var ldrInfo:LoaderInfo = e.currentTarget as LoaderInfo;
			trace( this, e.type, "\n\t", 
				StringUtil.getBaseName(ldrInfo.url), "from\t", StringUtil.getBaseName(ldrInfo.loaderURL) );
		}
		
	}
	
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.text.TextField;
	/**
	 * ...
	 * @author wibrst@qq.com
	 */
}